<template>
  <div id="gaugenCpuMain" ref="chartGaugeCpu" style="width:100%; height:265px;"></div>
</template>

<script>
import { getCpu } from '@/api/home'
import resize from './mixins/resize'
export default {
  mixins: [resize],
  data () {
    return {
      chart: null,
      gaugeData: 0
    }
  },
  mounted () {
    this.initChart()
    // this.$nextTick(() => async function () {
    //   await this.listData()
    //   this.timerGaugeCpu = setInterval(() => async function () {
    //     await this.listData()
    //   }, 30000)
    // })
  },
  beforeDestroy () {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    if (this.timerGaugeCpu) {
      clearInterval(this.timerGaugeCpu) // 在Vue实例销毁前，清除我们的定时器
    }
  },
  methods: {
    init () {
      // await this.initChart()
      //   this.listData()
      // },
      // listData (val) {
      return new Promise((resolve, reject) => {
        getCpu().then(res => {
          if (res.status === 0) {
            this.gaugeData = res.info[0].usage
            this.chart.setOption(this.option(this.gaugeData), true)
          }
          resolve('s')
        }).catch(e => {
          if (this.timerGaugeCpu) {
            clearInterval(this.timerGaugeCpu)
          }
          resolve('s')
        })
      })
    },
    option (val) {
      var data = {
        series: [{
          type: 'gauge',
          axisLine: {
            lineStyle: {
              width: 17,
              color: [
                [0.3, '#009966'],
                [0.7, '#fac858'],
                [1, '#fd666d']
              ]
            }
          },
          pointer: {
            itemStyle: {
              color: 'auto'
            }
          },
          axisTick: {
            distance: -17,
            length: 5,
            lineStyle: {
              color: '#fff',
              width: 2
            }
          },
          splitLine: {
            distance: -17,
            length: 18,
            lineStyle: {
              color: '#fff',
              width: 3
            }
          },
          axisLabel: {
            color: 'auto',
            distance: 22,
            fontSize: 12
          },
          detail: {
            valueAnimation: true,
            formatter: '{value}%',
            offsetCenter: [0, '90%'],
            fontSize: 20,
            color: 'auto'
          },
          data: [{
            value: val.toFixed(2),
            name: 'CPU'
          }]
        }]
      }
      return data
    },
    initChart () {
      this.chart = this.$echarts.init(this.$el)
      // this.chart.setOption(this.option(this.gaugeData), true)
    }
  }
}
</script>
